import React, { useState, useEffect } from 'react';
import type { AssessmentType, BusinessSystem } from '@/types/business';
import { useBusiness } from '@/stores/useBusinessStore';
import type { TemplateTable } from '@/types/template';
import { FiArrowLeft, FiArrowRight, FiCheck } from 'react-icons/fi';

interface CreateBusinessModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSubmit: (business: Omit<BusinessSystem, 'id' | 'createdAt' | 'status'>) => void;
  businessToEdit?: BusinessSystem | null;
  isEditing: boolean;
}

const CreateBusinessModal: React.FC<CreateBusinessModalProps> = ({ 
  isOpen, 
  onClose, 
  onSubmit,
  businessToEdit,
  isEditing
}) => {
  const today = new Date().toISOString().split('T')[0];
  const { fetchTemplates } = useBusiness();
  const [templates, setTemplates] = useState<TemplateTable[]>([]);
  const [isLoadingTemplates, setIsLoadingTemplates] = useState(false);
  
  const [currentStep, setCurrentStep] = useState(1);
  const [formData, setFormData] = useState({
    // 步骤1: 系统信息
    name: '',
    ratingFilingName: '',
    // 步骤2: 负责人信息
    responsiblePerson: '',
    businessDepartment: '',
    contact: '',
    // 步骤3: 评估类型和模板
    templateID: '',
    assessmentType: '101' as AssessmentType,
    // 步骤4: 预计完成时间
    expectedCompletionDate: '',
  });
  
  const [errors, setErrors] = useState<Record<string, string>>({});

  // Load templates when assessment type changes
  useEffect(() => {
    const loadTemplates = async () => {
      if (!formData.assessmentType) return;
      
      setIsLoadingTemplates(true);
      try {
        const templates = await fetchTemplates(formData.assessmentType as '101' | '102');
        setTemplates(templates);
      } catch (error) {
        console.error('Failed to load templates:', error);
      } finally {
        setIsLoadingTemplates(false);
      }
    };

    loadTemplates();
  }, [formData.assessmentType, fetchTemplates]);

  // If editing, populate form with business data
  useEffect(() => {
    if (isEditing && businessToEdit) {
      setFormData({
        name: businessToEdit.name,
        ratingFilingName: businessToEdit.ratingFilingName,
        responsiblePerson: businessToEdit.responsiblePerson,
        businessDepartment: businessToEdit.businessDepartment,
        contact: businessToEdit.contact,
        templateID: businessToEdit.templateID,
        assessmentType: businessToEdit.assessmentType,
        expectedCompletionDate: businessToEdit.expectedCompletionDate,
      });

      // Load templates for the assessment type of the business being edited
      const loadTemplateForEdit = async () => {
        setIsLoadingTemplates(true);
        try {
          const templates = await fetchTemplates(
            businessToEdit.assessmentType.toString() as '101' | '102'
          );
          setTemplates(templates);
        } catch (error) {
          console.error('Failed to load templates for edit:', error);
        } finally {
          setIsLoadingTemplates(false);
        }
      };
      
      loadTemplateForEdit();
    } else {
      // Reset form when opening for create
      setFormData({
        name: '',
        ratingFilingName: '',
        responsiblePerson: '',
        businessDepartment: '',
        contact: '',
        templateID: '',
        assessmentType: '101',
        expectedCompletionDate: '',
      });
    }
  }, [isEditing, businessToEdit, fetchTemplates]);

  // Handle input changes
  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    
    // Reset templateID when assessment type changes
    if (name === 'assessmentType') {
      setFormData(prev => ({ ...prev, [name]: value as AssessmentType, templateID: '' }));
    } else {
      setFormData(prev => ({ ...prev, [name]: value }));
    }
    
    // Clear error when field is edited
    if (errors[name]) {
      setErrors(prev => ({ ...prev, [name]: '' }));
    }
  };

  // Validate form
  const validateForm = () => {
    const newErrors: Record<string, string> = {};
    
    if (!formData.name.trim()) {
      newErrors.name = '业务系统名称不能为空';
    }
    
    if (!formData.ratingFilingName.trim()) {
      newErrors.ratingFilingName = '定级备案名称不能为空';
    }
    
    if (!formData.responsiblePerson.trim()) {
      newErrors.responsiblePerson = '负责人姓名不能为空';
    }
    
    if (!formData.businessDepartment.trim()) {
      newErrors.businessDepartment = '业务负责人部门不能为空';
    }
    
    if (!formData.contact.trim()) {
      newErrors.contact = '联系方式不能为空';
    } else {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      const phoneRegex = /^1[3-9]\d{9}$/;
      
      if (!emailRegex.test(formData.contact) && !phoneRegex.test(formData.contact)) {
        newErrors.contact = '请输入有效的邮箱或手机号';
      }
    }
    
    if (!formData.templateID) {
      newErrors.templateID = '请选择模板表';
    }
    
    if (!formData.expectedCompletionDate) {
      newErrors.expectedCompletionDate = '请选择预计完成时间';
    } else if (formData.expectedCompletionDate <= today) {
      newErrors.expectedCompletionDate = '预计完成时间必须晚于今天';
    }
    
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  // Handle form submission
  const handleNext = (e: React.MouseEvent<HTMLButtonElement>) => {
    // 阻止按钮在同一次点击中因 DOM 更新变为 submit 而触发默认提交
    e.preventDefault();
    if (validateCurrentStep()) {
      setCurrentStep(prev => prev + 1);
    }
  };

  const handleBack = () => {
    setCurrentStep(prev => prev - 1);
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    
    if (validateForm()) {
      onSubmit({
        name: formData.name,
        ratingFilingName: formData.ratingFilingName,
        responsiblePerson: formData.responsiblePerson,
        businessDepartment: formData.businessDepartment,
        contact: formData.contact,
        templateID: formData.templateID,
        assessmentType: formData.assessmentType,
        expectedCompletionDate: formData.expectedCompletionDate,
      });
      
      // Reset form
      setFormData({
        name: '',
        ratingFilingName: '',
        responsiblePerson: '',
        businessDepartment: '',
        contact: '',
        templateID: '',
        assessmentType: '101',
        expectedCompletionDate: '',
      });
      
      setCurrentStep(1);
      onClose();
    }
  };

  const validateCurrentStep = () => {
    const newErrors: Record<string, string> = {};
    
    if (currentStep === 1) {
      if (!formData.name.trim()) newErrors.name = '业务系统名称不能为空';
      if (!formData.ratingFilingName.trim()) newErrors.ratingFilingName = '定级备案名称不能为空';
    } 
    else if (currentStep === 2) {
      if (!formData.responsiblePerson.trim()) newErrors.responsiblePerson = '负责人姓名不能为空';
      if (!formData.businessDepartment.trim()) newErrors.businessDepartment = '业务负责人部门不能为空';
      if (!formData.contact.trim()) {
        newErrors.contact = '联系方式不能为空';
      } else {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        const phoneRegex = /^1[3-9]\d{9}$/;
        
        if (!emailRegex.test(formData.contact) && !phoneRegex.test(formData.contact)) {
          newErrors.contact = '请输入有效的邮箱或手机号';
        }
      }
    }
    else if (currentStep === 3) {
      if (!formData.templateID) newErrors.templateID = '请选择模板表';
    }
    else if (currentStep === 4) {
      if (!formData.expectedCompletionDate) {
        newErrors.expectedCompletionDate = '请选择预计完成时间';
      } else if (formData.expectedCompletionDate <= today) {
        newErrors.expectedCompletionDate = '预计完成时间必须晚于今天';
      }
    }
    
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const renderStepIndicator = () => {
    const steps = [
      { number: 1, label: '系统信息' },
      { number: 2, label: '负责人信息' },
      { number: 3, label: '评估类型' },
      { number: 4, label: '完成时间' },
      { number: 5, label: '确认信息' },
    ];

    return (
      <div className="flex justify-between w-full mb-8">
        {steps.map((step) => (
          <div key={step.number} className="flex flex-col items-center">
            <div 
              className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium
                ${currentStep >= step.number 
                  ? 'bg-blue-600 text-white' 
                  : 'bg-gray-200 text-gray-600'}`}
            >
              {currentStep > step.number ? <FiCheck className="w-4 h-4" /> : step.number}
            </div>
            <span className={`text-xs mt-2 ${currentStep >= step.number ? 'text-blue-600 font-medium' : 'text-gray-500'}`}>
              {step.label}
            </span>
          </div>
        ))}
      </div>
    );
  };

  const renderFormStep = () => {
    switch (currentStep) {
      case 1:
        return (
          <div className="space-y-4">
            <h3 className="text-lg font-medium mb-4">系统信息</h3>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">业务系统名称 *</label>
              <input
                type="text"
                name="name"
                value={formData.name}
                onChange={handleChange}
                className={`w-full px-3 py-2 border rounded-md ${errors.name ? 'border-red-500' : 'border-gray-300'
                  }`}
                placeholder="请输入业务系统名称"
              />
              {errors.name && <p className="mt-1 text-sm text-red-600">{errors.name}</p>}
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">定级备案名称 *</label>
              <input
                type="text"
                name="ratingFilingName"
                value={formData.ratingFilingName}
                onChange={handleChange}
                className={`w-full px-3 py-2 border rounded-md ${errors.ratingFilingName ? 'border-red-500' : 'border-gray-300'
                  }`}
                placeholder="请输入定级备案名称"
              />
              {errors.ratingFilingName && <p className="mt-1 text-sm text-red-600">{errors.ratingFilingName}</p>}
            </div>
          </div>
        );

      case 2:
        return (
          <div className="space-y-4">
            <h3 className="text-lg font-medium mb-4">负责人信息</h3>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">负责人姓名 *</label>
              <input
                type="text"
                name="responsiblePerson"
                value={formData.responsiblePerson}
                onChange={handleChange}
                className={`w-full px-3 py-2 border rounded-md ${errors.responsiblePerson ? 'border-red-500' : 'border-gray-300'
                  }`}
                placeholder="请输入负责人姓名"
              />
              {errors.responsiblePerson && <p className="mt-1 text-sm text-red-600">{errors.responsiblePerson}</p>}
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">业务负责人部门 *</label>
              <input
                type="text"
                name="businessDepartment"
                value={formData.businessDepartment}
                onChange={handleChange}
                className={`w-full px-3 py-2 border rounded-md ${errors.businessDepartment ? 'border-red-500' : 'border-gray-300'
                  }`}
                placeholder="请输入业务负责人部门"
              />
              {errors.businessDepartment && <p className="mt-1 text-sm text-red-600">{errors.businessDepartment}</p>}
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">联系方式 *</label>
              <input
                type="text"
                name="contact"
                value={formData.contact}
                onChange={handleChange}
                className={`w-full px-3 py-2 border rounded-md ${errors.contact ? 'border-red-500' : 'border-gray-300'
                  }`}
                placeholder="请输入邮箱或手机号"
              />
              {errors.contact && <p className="mt-1 text-sm text-red-600">{errors.contact}</p>}
            </div>
          </div>
        );

      case 3:
        return (
          <div className="space-y-4">
            <h3 className="text-lg font-medium mb-4">评估类型</h3>
              <div className="mb-4">
              <label className="block text-sm font-medium text-gray-700 mb-2">评估类型</label>
              <select
                name="assessmentType"
                value={formData.assessmentType}
                onChange={handleChange}
                className="w-full px-3 py-2 border rounded-md bg-white shadow-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition border-gray-300"
              >
                <option value="101">双新评估</option>
                <option value="102">涉诈评估</option>
                <option value="103">智慧中台评估</option>
                <option value="104">5G应用安全评估</option>
                <option value="105">数据安全评估</option>
              </select>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">选择模板表 *</label>
              {isLoadingTemplates ? (
                <div className="text-sm text-gray-500">加载模板中...</div>
              ) : (
                <select
                  name="templateID"
                  value={formData.templateID}
                  onChange={handleChange}
                  className={`w-full px-3 py-2 border rounded-md bg-white shadow-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition ${errors.templateID ? 'border-red-500' : 'border-gray-300'}`}
                  disabled={isLoadingTemplates}
                >
                  <option value="">请选择模板表</option>
                  {templates.map((template) => (
                    <option key={template.id} value={template.id}>
                      {template.name}
                      {formData.assessmentType === '105' && template.default_maturity_level 
                        ? ` - 默认成熟度等级：${template.default_maturity_level}` 
                        : ''}
                    </option>
                  ))}
                </select>
              )}
              {errors.templateID && <p className="mt-1 text-sm text-red-600">{errors.templateID}</p>}
            </div>
          </div>
        );

      case 4:
        return (
          <div className="space-y-4">
            <h3 className="text-lg font-medium mb-4">预计完成时间</h3>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">预计完成时间 *</label>
              <input
                type="date"
                name="expectedCompletionDate"
                value={formData.expectedCompletionDate}
                min={new Date(new Date().setDate(new Date().getDate() + 1)).toISOString().split('T')[0]}
                onChange={handleChange}
                className={`w-full px-3 py-2 border rounded-md ${errors.expectedCompletionDate ? 'border-red-500' : 'border-gray-300'
                  }`}
              />
              {errors.expectedCompletionDate && (
                <p className="mt-1 text-sm text-red-600">{errors.expectedCompletionDate}</p>
              )}
            </div>
          </div>
        );

      case 5: {
        const selectedTemplate = templates.find((t) => t.id === formData.templateID);
        return (
          <div className="space-y-4">
            <h3 className="text-lg font-medium mb-4">确认信息</h3>
            <div className="p-4 rounded-md border border-gray-200 bg-white shadow-sm">
              <h4 className="font-semibold text-slate-800 mb-3">系统信息</h4>
              <div className="grid grid-cols-2 gap-4 text-sm text-slate-700">
                <div>
                  <p className="text-gray-500">业务系统名称</p>
                  <p>{formData.name}</p>
                </div>
                <div>
                  <p className="text-gray-500">定级备案名称</p>
                  <p>{formData.ratingFilingName}</p>
                </div>
              </div>

              <h4 className="font-semibold text-slate-800 mt-6 mb-3">负责人信息</h4>
              <div className="grid grid-cols-3 gap-4 text-sm text-gray-700">
                <div>
                  <p className="text-gray-500">负责人</p>
                  <p>{formData.responsiblePerson}</p>
                </div>
                <div>
                  <p className="text-gray-500">部门</p>
                  <p>{formData.businessDepartment}</p>
                </div>
                <div>
                  <p className="text-gray-500">联系方式</p>
                  <p>{formData.contact}</p>
                </div>
              </div>

              <h4 className="font-semibold text-slate-800 mt-6 mb-3">评估信息</h4>
              <div className="grid grid-cols-3 gap-4 text-sm text-gray-700">
                <div>
                  <p className="text-gray-500">评估类型</p>
                  <p>
                    {formData.assessmentType === '101' && '双新评估'}
                    {formData.assessmentType === '102' && '涉诈评估'}
                    {formData.assessmentType === '103' && '智慧中台评估'}
                    {formData.assessmentType === '104' && '5G应用安全评估'}
                    {formData.assessmentType === '105' && '数据安全评估'}
                  </p>
                </div>
                <div>
                  <p className="text-gray-500">模板表</p>
                  <p>
                    {selectedTemplate?.name || '未选择'}
                    {formData.assessmentType === '105' && selectedTemplate?.default_maturity_level 
                      ? ` (默认等级${selectedTemplate.default_maturity_level})` 
                      : ''}
                  </p>
                </div>
                <div>
                  <p className="text-gray-500">预计完成时间</p>
                  <p>{formData.expectedCompletionDate}</p>
                </div>
              </div>
            </div>
          </div>
        );
      }

      default:
        return null;
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div className="bg-white rounded-lg shadow-xl w-full max-w-2xl max-h-[90vh] overflow-y-auto">
        <div className="p-6">
          <div className="flex justify-between items-center mb-6">
            <h2 className="text-xl font-semibold text-gray-900">
              {isEditing ? '编辑业务系统' : '创建新业务系统'}
            </h2>
            <button
              onClick={onClose}
              className="text-gray-400 hover:text-gray-500"
              type="button"
            >
              <span className="sr-only">关闭</span>
              <svg className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </div>

          {/* 步骤指示器 */}
          {renderStepIndicator()}

          <form onSubmit={handleSubmit} className="space-y-6">
            {renderFormStep()}
            <div className="flex justify-between pt-4 border-t border-gray-200 mt-8">
              <div>
                {currentStep > 1 && (
                  <button
                    type="button"
                    onClick={handleBack}
                    className="inline-flex items-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
                  >
                    <FiArrowLeft className="-ml-1 mr-2 h-4 w-4" />
                    上一步
                  </button>
                )}
              </div>

              <div className="flex space-x-3">
                <button
                  type="button"
                  onClick={onClose}
                  className="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
                >
                  取消
                </button>

                {currentStep < 5 ? (
                  <button
                    type="button"
                    onClick={handleNext}
                    className="inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
                  >
                    下一步
                    <FiArrowRight className="ml-2 -mr-1 h-4 w-4" />
                  </button>
                ) : (
                  <button
                    type="submit"
                    className="inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500"
                  >
                    <FiCheck className="-ml-1 mr-2 h-4 w-4" />
                    {isEditing ? '确认更新' : '确认创建'}
                  </button>
                )}
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
};

export default CreateBusinessModal;